/**
 * TopNavBar.js
 * Provides the top navigation bar component for the Virtual Bank System
 */

class TopNavBar {
  constructor() {
    this.notifications = [];
    this.unreadCount = 0;
    this.user = null;
  }

  /**
   * Initialize the top navigation bar
   */
  init() {
    this.loadUserInfo();
    this.render();
    this.bindEvents();
  }

  /**
   * Load current user information
   */
  loadUserInfo() {
    // Try to get user info from localStorage (temporary storage between pages)
    const userInfo = localStorage.getItem('userInfo');
    if (userInfo) {
      this.user = JSON.parse(userInfo);
    }

    // If no user info is found, check if user is authenticated via API
    if (!this.user) {
      this.fetchUserInfo();
    }
  }

  /**
   * Fetch user information from the server
   */
  fetchUserInfo() {
    // Get the auth token from cookies
    const token = this.getAuthToken();
    
    if (!token) {
      // Redirect to login page if no token
      if (!window.location.pathname.includes('/login.html') && 
          !window.location.pathname.includes('/register.html')) {
        window.location.href = '/login.html';
      }
      return;
    }

    // Fetch user info from the API
    fetch('/api/user/info', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })
    .then(response => {
      if (!response.ok) {
        throw new Error('Failed to fetch user info');
      }
      return response.json();
    })
    .then(data => {
      if (data.code === 0 && data.data) {
        this.user = data.data;
        localStorage.setItem('userInfo', JSON.stringify(this.user));
        this.updateUserDisplay();
        
        // Load notifications after user is authenticated
        this.loadNotifications();
      } else {
        throw new Error(data.message || 'Failed to get user info');
      }
    })
    .catch(error => {
      console.error('Error fetching user info:', error);
      
      // If authentication error, redirect to login
      if (error.message.includes('authentication') || error.message.includes('token')) {
        this.logout();
      }
    });
  }

  /**
   * Load user notifications
   */
  loadNotifications() {
    const token = this.getAuthToken();
    
    if (!token) return;

    fetch('/api/notification/list?status=0&page=1&size=5', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })
    .then(response => response.json())
    .then(data => {
      if (data.code === 0 && data.data) {
        this.notifications = data.data.list || [];
        this.unreadCount = this.notifications.length;
        this.updateNotificationDisplay();
      }
    })
    .catch(error => {
      console.error('Error loading notifications:', error);
    });
  }

  /**
   * Get authentication token from cookies
   */
  getAuthToken() {
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
      const cookie = cookies[i].trim();
      if (cookie.startsWith('virtualbank_token=')) {
        return cookie.substring('virtualbank_token='.length, cookie.length);
      }
    }
    return null;
  }

  /**
   * Render the top navigation bar
   */
  render() {
    const headerElement = document.getElementById('top-navbar');
    
    if (!headerElement) {
      console.error('Header element not found');
      return;
    }

    let notificationBadge = '';
    if (this.unreadCount > 0) {
      notificationBadge = `<span class="notification-badge">${this.unreadCount}</span>`;
    }

    headerElement.innerHTML = `
      <div class="header">
        <button class="mobile-menu-btn" id="mobile-menu-toggle">
          <i class="fas fa-bars"></i>
        </button>
        <div class="logo">
          <img src="/images/logo.png" alt="Virtual Bank" />
          <span>Virtual Bank</span>
        </div>
        <div class="header-nav">
          <div class="header-nav-item notification-icon" id="notification-toggle">
            <i class="fas fa-bell"></i>
            ${notificationBadge}
            <div class="notification-dropdown" id="notification-dropdown">
              <div class="notification-header">
                <h3>通知</h3>
                <button class="btn-link" id="mark-all-read">全部标记为已读</button>
              </div>
              <div class="notification-list" id="notification-list">
                <div class="notification-empty">无通知</div>
              </div>
              <div class="notification-footer">
                <a href="/notifications.html">查看全部</a>
              </div>
            </div>
          </div>
          <div class="header-nav-item user-info" id="user-dropdown-toggle">
            <div class="user-avatar">
              <span id="user-avatar-text">U</span>
            </div>
            <span id="username">用户</span>
            <i class="fas fa-caret-down"></i>
            <div class="user-dropdown" id="user-dropdown">
              <a href="/profile.html"><i class="fas fa-user"></i> 个人中心</a>
              <a href="/settings.html"><i class="fas fa-cog"></i> 设置</a>
              <a href="#" id="logout-btn"><i class="fas fa-sign-out-alt"></i> 登出</a>
            </div>
          </div>
        </div>
      </div>
    `;

    this.updateUserDisplay();
    this.updateNotificationDisplay();
  }

  /**
   * Update user display with current user info
   */
  updateUserDisplay() {
    const usernameElement = document.getElementById('username');
    const avatarTextElement = document.getElementById('user-avatar-text');
    
    if (this.user && usernameElement && avatarTextElement) {
      usernameElement.textContent = this.user.username || '用户';
      avatarTextElement.textContent = (this.user.username && this.user.username.charAt(0).toUpperCase()) || 'U';
    }
  }

  /**
   * Update notification display
   */
  updateNotificationDisplay() {
    const notificationListElement = document.getElementById('notification-list');
    const notificationBadgeElement = document.querySelector('.notification-badge');
    
    if (!notificationListElement) return;

    if (this.notifications.length === 0) {
      notificationListElement.innerHTML = '<div class="notification-empty">无通知</div>';
    } else {
      notificationListElement.innerHTML = this.notifications.map(notification => `
        <div class="notification-item" data-id="${notification.id}">
          <div class="notification-content">
            <div class="notification-title">${notification.title}</div>
            <div class="notification-time">${this.formatTime(notification.createTime)}</div>
          </div>
          <button class="notification-mark-read" data-id="${notification.id}">
            <i class="fas fa-check"></i>
          </button>
        </div>
      `).join('');
    }

    // Update the badge count
    if (notificationBadgeElement) {
      if (this.unreadCount > 0) {
        notificationBadgeElement.textContent = this.unreadCount;
        notificationBadgeElement.style.display = 'block';
      } else {
        notificationBadgeElement.style.display = 'none';
      }
    }

    // Re-bind notification events
    this.bindNotificationEvents();
  }

  /**
   * Format timestamp to human-readable format
   */
  formatTime(timestamp) {
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;
    
    // If less than a day, show relative time
    if (diff < 24 * 60 * 60 * 1000) {
      if (diff < 60 * 1000) {
        return '刚刚';
      } else if (diff < 60 * 60 * 1000) {
        return `${Math.floor(diff / (60 * 1000))}分钟前`;
      } else {
        return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
      }
    } 
    
    // Otherwise show the date
    return date.toLocaleDateString();
  }

  /**
   * Bind events to the navigation bar elements
   */
  bindEvents() {
    // Toggle mobile menu
    const mobileMenuToggle = document.getElementById('mobile-menu-toggle');
    if (mobileMenuToggle) {
      mobileMenuToggle.addEventListener('click', () => {
        const sidebar = document.querySelector('.sidebar');
        if (sidebar) {
          sidebar.classList.toggle('mobile-visible');
        }
      });
    }

    // Toggle notification dropdown
    const notificationToggle = document.getElementById('notification-toggle');
    const notificationDropdown = document.getElementById('notification-dropdown');
    
    if (notificationToggle && notificationDropdown) {
      notificationToggle.addEventListener('click', (e) => {
        e.stopPropagation();
        notificationDropdown.classList.toggle('active');
        // Hide user dropdown if open
        const userDropdown = document.getElementById('user-dropdown');
        if (userDropdown && userDropdown.classList.contains('active')) {
          userDropdown.classList.remove('active');
        }
      });
    }

    // Toggle user dropdown
    const userDropdownToggle = document.getElementById('user-dropdown-toggle');
    const userDropdown = document.getElementById('user-dropdown');
    
    if (userDropdownToggle && userDropdown) {
      userDropdownToggle.addEventListener('click', (e) => {
        e.stopPropagation();
        userDropdown.classList.toggle('active');
        // Hide notification dropdown if open
        if (notificationDropdown && notificationDropdown.classList.contains('active')) {
          notificationDropdown.classList.remove('active');
        }
      });
    }

    // Close dropdowns when clicking outside
    document.addEventListener('click', () => {
      if (notificationDropdown && notificationDropdown.classList.contains('active')) {
        notificationDropdown.classList.remove('active');
      }
      if (userDropdown && userDropdown.classList.contains('active')) {
        userDropdown.classList.remove('active');
      }
    });

    // Prevent closing when clicking inside the dropdown
    if (notificationDropdown) {
      notificationDropdown.addEventListener('click', (e) => {
        e.stopPropagation();
      });
    }
    
    if (userDropdown) {
      userDropdown.addEventListener('click', (e) => {
        e.stopPropagation();
      });
    }

    // Logout button
    const logoutBtn = document.getElementById('logout-btn');
    if (logoutBtn) {
      logoutBtn.addEventListener('click', (e) => {
        e.preventDefault();
        this.logout();
      });
    }

    // Mark all notifications as read
    const markAllReadBtn = document.getElementById('mark-all-read');
    if (markAllReadBtn) {
      markAllReadBtn.addEventListener('click', () => {
        this.markAllNotificationsAsRead();
      });
    }

    this.bindNotificationEvents();
  }

  /**
   * Bind events specific to notification items
   */
  bindNotificationEvents() {
    // Mark individual notification as read
    const markReadButtons = document.querySelectorAll('.notification-mark-read');
    markReadButtons.forEach(button => {
      button.addEventListener('click', (e) => {
        e.stopPropagation();
        const notificationId = button.getAttribute('data-id');
        this.markNotificationAsRead(notificationId);
      });
    });

    // Click on notification to view details
    const notificationItems = document.querySelectorAll('.notification-item');
    notificationItems.forEach(item => {
      item.addEventListener('click', () => {
        const notificationId = item.getAttribute('data-id');
        this.viewNotificationDetails(notificationId);
      });
    });
  }

  /**
   * Mark a notification as read
   */
  markNotificationAsRead(notificationId) {
    const token = this.getAuthToken();
    
    if (!token) return;

    fetch(`/api/notification/read/${notificationId}`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })
    .then(response => response.json())
    .then(data => {
      if (data.code === 0) {
        // Update local state
        this.notifications = this.notifications.filter(n => n.id !== parseInt(notificationId));
        this.unreadCount = Math.max(0, this.unreadCount - 1);
        this.updateNotificationDisplay();
      }
    })
    .catch(error => {
      console.error('Error marking notification as read:', error);
    });
  }

  /**
   * Mark all notifications as read
   */
  markAllNotificationsAsRead() {
    const token = this.getAuthToken();
    
    if (!token) return;

    fetch('/api/notification/read-all', {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })
    .then(response => response.json())
    .then(data => {
      if (data.code === 0) {
        // Clear local notifications
        this.notifications = [];
        this.unreadCount = 0;
        this.updateNotificationDisplay();
      }
    })
    .catch(error => {
      console.error('Error marking all notifications as read:', error);
    });
  }

  /**
   * View notification details
   */
  viewNotificationDetails(notificationId) {
    window.location.href = `/notification-detail.html?id=${notificationId}`;
  }

  /**
   * Logout the user
   */
  logout() {
    const token = this.getAuthToken();
    
    if (token) {
      // Call the logout API
      fetch('/api/user/logout', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })
      .then(response => response.json())
      .then(data => {
        // Clear local storage and cookies regardless of API response
        this.clearUserData();
        window.location.href = '/login.html';
      })
      .catch(error => {
        console.error('Error during logout:', error);
        // Still clear data and redirect even if API fails
        this.clearUserData();
        window.location.href = '/login.html';
      });
    } else {
      // If no token, just redirect to login
      window.location.href = '/login.html';
    }
  }

  /**
   * Clear user data from browser
   */
  clearUserData() {
    // Clear localStorage
    localStorage.removeItem('userInfo');
    
    // Clear the auth token cookie
    document.cookie = 'virtualbank_token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
  }
}

// Export for use in other files
window.TopNavBar = TopNavBar;
